// websocket.ts

import { eventBus } from './eventBus';
import { useUserStore } from '@/stores/user';

class WebSocketService {
    private static instance: WebSocketService;
    private socket: WebSocket | null = null;
    private readonly url: string = import.meta.env.VITE_WEBSOCKET_URL;
    private reconnectAttempts: number = 0;
    private maxReconnectAttempts: number = 5; // 最大重连次数
  
    private constructor() {}
  
    // 获取单例实例
    public static getInstance(): WebSocketService {
      if (!WebSocketService.instance) {
        WebSocketService.instance = new WebSocketService();
      }
      return WebSocketService.instance;
    }
  
    // 初始化 WebSocket 连接
    public connect() {
      const user = useUserStore();
      if (user.loginstatus&&(!this.socket || this.socket.readyState !== WebSocket.OPEN)) {
        this.socket = new WebSocket(`${process.env.NODE_ENV != "development" ? "http://124.220.165.240:9999/" : "http://localhost:9999/"}ws/${user.token}`);
  
        this.socket.onopen = () => {
          console.log('WebSocket connected');
          this.reconnectAttempts = 0; // 重置重连次数
        };
  
        this.socket.onmessage = (event) => {
          const data = JSON.parse(event.data);

          eventBus.emit('message-received', data);
        };
        this.socket.onerror = (error) => {
          console.error('WebSocket error:', error);
        };
        
  
        this.socket.onclose = () => {
          console.log('WebSocket connection closed');
  if (this.reconnectAttempts < this.maxReconnectAttempts) {
    setTimeout(() => {
      this.reconnectAttempts++;
      console.log(`Reconnecting attempt ${this.reconnectAttempts}`);
      this.connect(); // 尝试重新连接
    }, 2000); // 每隔2秒重连一次
  } else {
    console.log('Max reconnect attempts reached');
  }
        };
  
        
      }
    }
  
    // 发送消息
    public send(message: string) {
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {
        this.socket.send(message);
      } else {
        console.error('WebSocket is not connected');
      }
    }
  // websocket.ts



    // 关闭连接
    public close() {
      if (this.socket) {
        this.socket.close();
      }
    }
  }
  export interface WebSocketMessageInterface {  type: string, data: any}
  export default WebSocketService.getInstance();
  